#include "qtvisio.h"
#include "ui_qtvisio.h"

QtVisio::QtVisio(QWidget *parent,QString pseudo) :
    QMainWindow(parent),
    _ui(new Ui::QtVisio)
{
    _ui->setupUi(this);
    _dataSize=0;
    _pseudo=pseudo;
    _ui->welcome->setText(_ui->welcome->text()+" "+_pseudo+"!");
}

QtVisio::~QtVisio()
{
    delete _ui;
}

void QtVisio::setServerSocket(QTcpSocket * serverSocket){

    _serverSocket=serverSocket;
    connect(_serverSocket, SIGNAL(readyRead()), this, SLOT(newData()));

}
void QtVisio::on_sendButton_clicked(){

    QByteArray packet;
    QDataStream out(&packet, QIODevice::WriteOnly);

    QString messageToSend = "<strong>"+_pseudo+"</strong> : "+ _ui->message->text();

    out << (quint16) 0;
    out << messageToSend;
    out.device()->seek(0);
    out << (quint16) (packet.size() - sizeof(quint16));

    _serverSocket->write(packet);

    _ui->message->clear();
    _ui->message->setFocus();
}

void QtVisio::newData(){

    QDataStream in(_serverSocket);

       if ( _dataSize == 0)
       {
           if (_serverSocket->bytesAvailable() < (int)sizeof(quint16))
                return;

           in >> _dataSize;
       }

       if (_serverSocket->bytesAvailable() < _dataSize)
           return;


       // Si on arrive jusqu'à cette ligne, on peut récupérer le message entier
       QString messageRecu;
       in >> messageRecu;

       // On affiche le message sur la zone de Chat
       _ui->chat->append(messageRecu);

       // On remet la taille du message à 0 pour pouvoir recevoir de futurs messages
       _dataSize = 0;

}
